#ifdef SYPX_MEMCHECK
#include "mmgr.h"
#endif
#include "SpriteInstance.h"

namespace SypX
{

	SpriteInstance::SpriteInstance(void):activeAction(0), activeFrame(0), activeAngle(0)
	{
	}

	SpriteInstance::~SpriteInstance(void)
	{
	}

	void SpriteInstance::update()
	{
		MeshInstance::update();
		sprite->bufferInstance(this);
	}

	void SpriteInstance::update(float elapsed)
	{
		MeshInstance::update();
		currTime += elapsed;			//update spriteInstance's time
		Sprite::SpriteActions& action = sprite->actions[activeAction];
		
		while( currTime > action.frameDuration[activeFrame] )
		{//if we exceed currentFrame's duration
			currTime -= action.frameDuration[activeFrame];	//compensate for current frame's duration
			nextFrame();									//change to next frame
		}	
		sprite->bufferInstance(this);

	}

	void SpriteInstance::useSprite(Sprite* s)
	{
		sprite = s;
		useMesh(s);
		useTexture(s->getTexture());
	}

	void SpriteInstance::setActiveAction(const String& actionName)
	{
		for(size_t i = 0; i < sprite->actions.size(); ++i)
		{
			if(sprite->actions[i].actionName == actionName)
			{
				setActiveAction( static_cast<UByte>(i) );
				return;
			}
		}
		assert(false && "Action not found for sprite.");
	}

	void SpriteInstance::setActiveAction(UByte index)
	{
		assert(index < sprite->actions.size() && "setActiveAction called with out of bounds index");
		activeAction = index;		
	}

	void SpriteInstance::setActiveFrame(UByte frame)
	{
		//Ensure frame is not beyond total number of frames
		assert( frame < sprite->actions[activeAction].numFrames );
		activeFrame = frame;		
	}

	void SpriteInstance::setActiveAngle(UByte angle)
	{
		assert( angle < 12 && "Angle must be from 0 - 11 only.");
		activeAngle = angle;		
	}

	UByte SpriteInstance::getActiveAction()
	{
		return activeAction;
	}
	
	UByte SpriteInstance::getActiveFrame()
	{
		return activeFrame;
	}
		
	UByte SpriteInstance::getActiveAngle()
	{
		return activeAngle;
	}

	void SpriteInstance::nextFrame()
	{
		++activeFrame;
		if(activeFrame >= sprite->actions[activeAction].numFrames )
		{
			activeFrame = 0;
		}
	}

	Sprite* SpriteInstance::getSprite()
	{
		return sprite;
	}

}